<template>
  <CustomDrawer
    v-model="show"
    ref="drawer"
    class="action-drawer"
    title="设置阀值"
    :width="420"
    @on-close="hideDrawer">
    <Form
      ref="JformData"
      class="form"
      :label-width="100"
      :model="formData"
      :rules="formRules">
      <CustomFormItem prop="run1Value" label="电流1#阀值">
        <CustomInput
          v-model="formData.run1Value"
          placeholder="电流1#阀值"
          type="number"
          :number="true" />
      </CustomFormItem>
      <CustomFormItem prop="run2Value" label="电流2#阀值">
        <CustomInput
          v-model="formData.run2Value"
          placeholder="电流2#阀值"
          type="number"
          :number="true" />
      </CustomFormItem>
      
      <div class="Buttons">
        <div class="Button-detail">
          <CustomButton
            type="primary"
            :loading="loading"
            @click="actionClick">提交保存</CustomButton>
        </div>
      </div>
    </Form>
  </CustomDrawer>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import { rules } from '../js/rules'

export default {
  emits: ['refreshTable'],
  computed: {
    ...mapState({
      'formInfo': state => state.realtimeNwdl.formInfo
    })
  },
  created () {
    this.formRules = rules(this)
  },
  data () {
    return {
      formData: {},
      loading: false,
      show: false
    }
  },
  methods: {
    initData () {
      const data = JSON.parse(JSON.stringify(this.formInfo))

      this.formData = data
    },
    initFormData () {
      this.formData = {}
      
      this.$refs['JformData'].resetFields()
    },
    showDrawer () {
      this.initData()
      this.show = true
    },
    // 关闭弹窗
    hideDrawer () {
      this.show = false

      setTimeout(() => {
        this.initFormData()
      }, 200)
    },
    // 触发表单保存按钮
    actionClick () {
      if (this.loading) {
        return
      }
      console.log('this.formData', this.formData)
      this.$refs.JformData.validate((val) => {
        if (val) {
          const data = {}

          data.addr = this.formData.addr
          data.run1Value = this.formData.run1Value
          data.run2Value = this.formData.run2Value

          this.saveData(data)
        }
      })
    },
    // 提交表单
    async saveData (data) {
      this.loading = true

      const url = `/GmnwApi/deviceRealRecord/editDeviceInfo`

      const res = await this.SUBMIT_FORM_FORMDATA({
        listUrl: url,
        data
      })

      this.loading = false

      if (res) {
        this.$emit('refreshTable')
        this.hideDrawer()
      }
    },
    ...mapActions({
      'SUBMIT_FORM_FORMDATA': 'SUBMIT_FORM_FORMDATA'
    })
  }
}
</script>

<style lang="scss" scoped>

</style>
